package com.AuthServer.config.filter;

import com.AuthServer.exception.LoginStatusInvalidException;
import com.AuthServer.pojo.entity.User;
import com.AuthServer.service.SecretService;
import com.AuthServer.utils.JsonUtil;
import com.AuthServer.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    @Qualifier("default")
    private RedisTemplate<String,Object> template;

    @Autowired
    private SecretService secretService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //取得token
        String token = request.getHeader("Authorization");
        if(token == null) {
            doFilter(request,response,filterChain);
            return ;
        }
        System.out.println(token);
        //token = token.substring(7).trim(); // 删除token前缀 "Bearer "
        String userInfo = (String) template.opsForValue().get(JwtUtil.parseJwt(token,template,secretService));
        if(userInfo == null){
            throw new LoginStatusInvalidException();
        }
        User user = JsonUtil.deserialize(userInfo, User.class);
        //根据用户信息和权限信息填充authenticationToken
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
        //设置security的上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        doFilter(request,response,filterChain);
    }
}
